package com.alex.jbpm.apply.decision;

import java.util.List;

import org.hibernate.Session;
import org.jbpm.context.exe.ContextInstance;
import org.jbpm.graph.def.Node;
import org.jbpm.graph.def.Transition;
import org.jbpm.graph.exe.ExecutionContext;
import org.jbpm.graph.exe.ProcessInstance;
import org.jbpm.graph.node.DecisionHandler;

import com.alex.jbpm.HibernateUtils;
import com.alex.jbpm.domain.Document;


public class SchoolDecisionHandler implements DecisionHandler {

	private static final long serialVersionUID = 4975657406225459651L;

	public String decide(ExecutionContext context) throws Exception {
		ContextInstance ci = context.getContextInstance();
		String documentId = ci.getVariable("documentId").toString();
		Session session = HibernateUtils.getSession();
		Document doc = (Document)session.load(Document.class, Integer.valueOf(documentId));
		ProcessInstance processInstance = ci.getProcessInstance();
		Node node = processInstance.getRootToken().getNode();
		String condition = doc.getCreator();
		String resultStr = null;
		if("1".equals(condition)){
			ci.setVariable("actorLevel", "department");
//			resultStr = "提交到中央审批";
			System.out.println("----------中央--------------");
			resultStr = getTransitionByCondition("中央", node);
		}else if("2".equals(condition)){
			ci.setVariable("actorLevel", "sheng");
//			resultStr = "提交到省级审批";
			System.out.println("----------省级--------------");
			resultStr = getTransitionByCondition("省级", node);
		}else if("3".equals(condition)){
			ci.setVariable("actorLevel", "shi");
//			resultStr = "提交到市级审批";
			System.out.println("----------市级--------------");
			resultStr = getTransitionByCondition("市级", node);
		}else if("4".equals(condition)){
			ci.setVariable("actorLevel", "xian");
//			resultStr = "提交到县级审批";
			System.out.println("----------县级--------------");
			resultStr = getTransitionByCondition("县级", node);
		}
		return resultStr;
	}
	
	/**
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private String getTransitionByCondition(String condition,Node node){
		String returnStr = null;
		List<Transition> trans = (List<Transition>)node.getLeavingTransitionsList();
		for(Transition t : trans){
			if(t.getTo().getName().indexOf(condition) != -1){
				returnStr = t.getName();
			}
		}
		if(returnStr == null){
			trans.get(0).getName();
		}
		return returnStr;
	}
}
